package algorithm.leetcode

import kotlin.contracts.contract

object FlowerCalc {
    /**1,0,0,1,0,0
     * [0,0,1,0,1]
     * [0,0,0,0,1]
     * [1,0,1,0,1,0,1]
     * [0,0,0,0,0,0]
     * [1,0,0,0,0,1]
     */
    fun canPlaceFlowers(flowerbed: IntArray, n: Int): Boolean {
        var count = n
        val size = flowerbed.size
        if(size == 1 && flowerbed[0] == 0) return true

        for (i in 1 until size){
            if(flowerbed[i-1] == 0 && flowerbed[i] == 0){
                if(i-2 < 0){
                    flowerbed[i-1] = 1
                    count--
                }else if(i + 1 >= size){
                    flowerbed[i] = 1
                    count--
                }else{
                    flowerbed[i-1] = 1
                    if(flowerbed[i-2] != 0){
                        flowerbed[i-1] = 0
                        flowerbed[i] = 1
                        if(flowerbed[i + 1] != 0){
                            continue
                        }
                    }
                    count--
                }
                if(count <= 0) return true
            }
        }
        return count <= 0
    }

    fun canPlaceFlowers2(flowerbed: IntArray, n: Int): Boolean {
        var count = n
        var i = 0
        while (i < flowerbed.size){
            if(flowerbed[i] == 1){
                i += 2
            }else if(i == flowerbed.size-1 || flowerbed[i+1] == 0){
                count--
                i += 2
            }else{
                i += 3
            }
            if(count <= 0) return true
        }
        return count <= 0
    }
}

fun main() {
    println(FlowerCalc.canPlaceFlowers(intArrayOf(0,0,0,0,1), 2))
}